package com.example.item01.aop;


import com.alibaba.fastjson.JSONObject;
import com.example.item01.mapper.OperateLogMapper;
import com.example.item01.proj.OperateLog;
import com.example.item01.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Slf4j
@Component
@Aspect

public class LogAspect {

    @Autowired

    private OperateLogMapper operateLogMapper;

    @Autowired

    private HttpServletRequest httpServletRequest;


    @Around("@annotation(com.example.item01.anno.Log)")
    public Object recodeLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //jwt令牌
        //操作人ID
        String token = httpServletRequest.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer operateUser = (Integer) claims.get("id");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //操作类名
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        //操作方法
        String methodName = proceedingJoinPoint.getSignature().getName();
        //操作方法参数
        Object[] args = proceedingJoinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        //方法返回值
        long begin = System.currentTimeMillis();
        Object resutl = proceedingJoinPoint.proceed();
        String returnValue = JSONObject.toJSONString(resutl);
        long end = System.currentTimeMillis();
        //时差
        Long costTime = end - begin;


        OperateLog operateLog=new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime);
        operateLogMapper.insert(operateLog);
        log.info("日志对象是{}",operateLog);
        return resutl;
    }


}
